package com.lorizz.model.impl;

import java.io.ByteArrayInputStream;
import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.HibernateException;

import com.lorizz.model.AbstractMutableType;
import com.lorizz.model.Meta;

public class BlobMetaType extends AbstractMutableType {

    @Override
    public Object deepCopy(Object value) throws HibernateException {
        if (value == null)
            return null;
        return ((Meta) value).copy();
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
            throws HibernateException, SQLException {
        Blob blob = rs.getBlob(names[0]);
        return (blob == null) ? new MetaImpl() : new MetaImpl(blob.getBytes(1,
                (int) blob.length()));
    }

    @Override
    public void nullSafeSet(PreparedStatement stat, Object value, int index)
            throws HibernateException, SQLException {
        MetaImpl meta = (MetaImpl) value;
        if (meta.getBytes() == null)
            stat.setNull(index, Types.BLOB);
        else
            stat.setBlob(index, new ByteArrayInputStream(meta.getBytes()));
    }

    @Override
    public Class<Meta> returnedClass() {
        return Meta.class;
    }

    @Override
    public int[] sqlTypes() {
        return new int[] { Types.BLOB };
    }

}
